<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true">
            添加角色
          </el-button>
        </el-col>
      </el-row>

      <!-- 角色列表 -->
      <el-table :data="rolesList" stripe border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :gutter="20"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="[
                'border-bottom',
                i1 === 0 ? 'border-top' : '',
                'vcenter'
              ]"
            >
              <!-- 一级权限渲染 -->
              <el-col :span="5">
                <el-tag
                  type="danger"
                  closable
                  @close="removeRightsById(scope.row, item1.id)"
                >
                  {{ item1.authName }}
                  <i class="el-icon-caret-right"></i>
                </el-tag>
              </el-col>
              <!-- 二 三级权限渲染 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'border-top', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="warning"
                      closable
                      @close="removeRightsById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                      <i class="el-icon-caret-right"></i>
                    </el-tag>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="success"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightsById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

            <!-- <pre>
              {{ scope.row }}
            </pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditRolesDialog(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRolesById(scope.row.id)"
            >
              删除
            </el-button>
            <el-tooltip
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRightsDialog(scope.row)"
              >
                分配权限
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加角色弹窗 -->
      <el-dialog
        title="添加角色"
        :visible.sync="addRoleDialogVisible"
        width="50%"
        @close="addRoleDialogClosed"
      >
        <!-- 内容主体 -->
        <el-form
          ref="addRoleFormRef"
          :model="addRoleForm"
          :rules="addRolesFules"
          label-width="80px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑角色 -->
      <el-dialog
        title="添加角色"
        :visible.sync="editRoleDialogVisible"
        width="50%"
        @close="editRoleDialogClosed"
      >
        <!-- 内容主体 -->
        <el-form
          ref="editRoleFormRef"
          :model="editRoleForm"
          :rules="addRolesFules"
          label-width="80px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRolesInfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配权限弹框 -->
      <el-dialog
        title="提示"
        :visible.sync="setRightsDialogVisible"
        width="50%"
        @close="setRightsDialogClosed"
      >
        <el-tree
          :data="rightsList"
          :props="treeProps"
          show-checkbox
          default-expand-all
          node-key="id"
          :default-checked-keys="defaultKeys"
          ref="allotRightsRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 添加角色弹窗是否关闭
      addRoleDialogVisible: false,
      // 添加角色表单信息
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加 编辑 角色验证规则
      addRolesFules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 6, message: '长度最少六个字符', trigger: 'blur' }
        ]
      },
      // 编辑角色弹窗是否关闭
      editRoleDialogVisible: false,
      // 编辑角色表单信息
      editRoleForm: {},
      // 控制分配权限弹框
      setRightsDialogVisible: false,
      // 权限数据
      rightsList: [],
      // 树形结构显示对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选择的节点 id值
      defaultKeys: [],
      // 当前角色id
      rolesId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
    },
    // 添加角色
    addRoles() {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addRoleDialogVisible = false
        this.getRolesList()
      })
    },
    // 添加角色弹框关闭事件
    addRoleDialogClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },
    // 编辑角色弹框关闭事件
    editRoleDialogClosed() {
      this.$refs.editRoleFormRef.resetFields()
    },
    // 编辑角色 首先弹出框填充信息
    async showEditRolesDialog(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editRoleForm = res.data
      this.editRoleDialogVisible = true
    },
    // 编辑角色 表单预校验 确认完成
    editRolesInfo() {
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.editRoleForm.roleId,
          {
            roleName: this.editRoleForm.roleName,
            roleDesc: this.editRoleForm.roleDesc
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('更新角色成功！')
        this.editRoleDialogVisible = false
        this.getRolesList()
      })
    },
    // 根据id删除对应角色
    async removeRolesById(id) {
      const resultConfirm = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 如果点击确认按钮  返回字符串 confirm
      // 如果点击取消按钮  返回字符串 cancel
      if (resultConfirm !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
    },
    // 根据id删除对应权限
    async removeRightsById(roles, rightsId) {
      const resultConfirm = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 如果点击确认按钮  返回字符串 confirm
      // 如果点击取消按钮  返回字符串 cancel
      if (resultConfirm !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete(
        `roles/${roles.id}/rights/${rightsId}`
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      //  注意 重新渲染权限列表就可以  此处的 roles 就是当前角色 scope.row
      // 如果重新加载  this.getRolesList() 没必要
      roles.children = res.data
    },
    // 是否展开分配权限对话框
    async showSetRightsDialog(roles) {
      // 在打开分配权限对话框的同时  把当前角色的id保存下来 方便后续使用
      this.rolesId = roles.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rightsList = res.data
      this.getLeafKeys(roles, this.defaultKeys)
      this.setRightsDialogVisible = true
    },
    //  利用递归 获取所有三级权限的id
    getLeafKeys(node, arr) {
      // 如果该节点没有children属性  说明已经是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      // 如果不是三级节点, 利用递归, 找到三级节点并保存id值
      node.children.forEach(item => {
        return this.getLeafKeys(item, arr)
      })
    },
    // 当每次权限对话框关闭后 需要清空里边的id值
    setRightsDialogClosed() {
      this.defaultKeys = []
    },
    // 进行权限分配
    async allotRights() {
      // 获取所有全选和半选中状态的id值
      const rids = [
        ...this.$refs.allotRightsRef.getCheckedKeys(),
        ...this.$refs.allotRightsRef.getHalfCheckedKeys()
      ]
      const idStr = rids.join(',')
      const {
        data: res
      } = await this.$http.post(`roles/${this.rolesId}/rights`, { rids: idStr })

      if (res.meta.status !== 200) return this.$message.error('权限分配失败！')
      this.$message.success('分配权限成功！')
      this.getRolesList()
      this.setRightsDialogVisible = false
    }
  }
}
</script>
<style scoped>
.el-tag {
  margin: 7px;
}

.border-top {
  border-top: 1px solid #eee;
}

.border-bottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
